package com.wits100.av;

import android.content.Context;
import android.net.Uri;
import android.view.Surface;

import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;

/**
 * Created by terry on 2018-12-22.
 */

public class ExoLitePlayer implements LitePlayer {

    SimpleExoPlayer player;
    Context context;
    EventListener listener;
    int state;

    public ExoLitePlayer(Context context) {
        this.context = context;
        player = ExoPlayerFactory.newSimpleInstance(context);
    }

    @Override
    public void setEventListener(EventListener listener) {
        this.listener = listener;
    }

    @Override
    public void setDisplay(Surface surface) {
        player.setVideoSurface(surface);
    }

    @Override
    public boolean open(String url) {
        Uri uri = Uri.parse(url);

        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this.context,
                Util.getUserAgent(this.context, "yourApplicationName"));
        // This is the MediaSource representing the media to be played.
        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
                .createMediaSource(uri);
        // Prepare the player with the source.
        player.prepare(videoSource);

        return false;
    }

    @Override
    public void close() {
        player.release();
    }

    @Override
    public boolean isOpen() {
        return false;
    }

    @Override
    public void play() {
        setState(MediaType.STATE_PLAYING);
        player.setPlayWhenReady(true);
    }

    @Override
    public void stop() {
        setState(MediaType.STATE_STOPPED);
        player.stop();
    }

    @Override
    public boolean snap(String filepath) {
        return false;
    }

    @Override
    public boolean isFormatReady() {
        return false;
    }

    @Override
    public int getState() {
        return state;
    }

    protected void setState(int state) {
        this.state = state;
    }


}
